// src/components/TableSearch.tsx
import React from 'react';
import {
  Form,
  Input,
  Select,
  DatePicker,
  Button,
  Space,
  Card,
} from '@arco-design/web-react';
import allTypes from '@/utils/Data';
import dayjs from 'dayjs'; // 确保已安装 dayjs

const FormItem = Form.Item;

export interface SearchField {
  key: string;
  label: string;
  type: 'input' | 'select' | 'datePicker';
  options?: { label: string; value: string | number }[]; // 用于 select 类型
  dateRange?: boolean;
}

interface TableSearchProps {
  fields: SearchField[];
  onSearch: (values: Record<string, never>) => void;
}

const TableSearch: React.FC<TableSearchProps> = ({ fields, onSearch }) => {
  const [form] = Form.useForm();
  const timeData = allTypes.timeData;

  const handleSearch = () => {
    form.validate().then((values) => {
      const processedValues = { ...values };
      fields.forEach((field) => {
        if (field.type === 'datePicker' && field.dateRange) {
          if (processedValues[field.key]) {
            const [start, end] = processedValues[field.key];
            processedValues[`StartDate`] = start
              ? dayjs(start).format('YYYY-MM-DD')
              : undefined;
            processedValues[`EndDate`] = end
              ? dayjs(end).format('YYYY-MM-DD')
              : undefined;
            delete processedValues[field.key];
          }
        }
      });
      onSearch(processedValues);
    });
  };

  const handleReset = () => {
    form.resetFields();
    onSearch({});
  };

  const renderField = (field: SearchField) => {
    switch (field.type) {
      case 'input':
        return <Input placeholder={`请输入${field.label}`} />;
      case 'select':
        return (
          <Select style={{ width: 200 }} placeholder={`请选择${field.label}`}>
            {field.options?.map((option) => (
              <Select.Option key={option.value} value={option.value}>
                {option.label}
              </Select.Option>
            ))}
          </Select>
        );
      case 'datePicker':
        return (
          <DatePicker.RangePicker
            shortcuts={timeData}
            style={{ width: '100%' }}
          />
        );
      default:
        return null;
    }
  };

  return (
    <Card style={{ marginBottom: 20 }}>
      <Form
        form={form}
        layout="inline"
        autoComplete="off"
        initialValues={{ type: null, time: null }}
        style={{ marginBottom: 16 }}
      >
        {fields.map((field) => (
          <FormItem key={field.key} label={field.label} field={field.key}>
            {renderField(field)}
          </FormItem>
        ))}
        <FormItem>
          <Space>
            <Button type="primary" onClick={handleSearch}>
              搜索
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </FormItem>
      </Form>
    </Card>
  );
};

export default TableSearch;
